import 'package:airbnb_clone/internal/cache/app_cache.dart';
import 'package:dio/dio.dart';

import '../request/base_request.dart';
import 'hi_adapter.dart';

class DioAdapter extends HiNetAdapter {
  Future<HiNetResponse<T>> buildRes<T>(
      Response? response, BaseRequest request) {
    return Future.value(HiNetResponse(
        data: response?.data,
        request: request,
        statusCode: response?.statusCode,
        statusMessage: response?.statusMessage,
        extra: response));
  }

  @override
  Future<HiNetResponse<T>> send<T>(BaseRequest request) async {
    Response? response;
    var options = Options(headers: request.header);
    if (request.needLogin()) {
      String? token = AppCache.token;
      request.addHeader("Authorization", token!);
    }
    try {
      if (request.httpMethod() == HttpMethod.GET) {
        response = await Dio().get(request.url(), options: options);
      } else if (request.httpMethod() == HttpMethod.POST) {
        if (request.userJsonAppcalition() == true) {
          response = await Dio()
              .post(request.url(), options: options, data: request.jsonData);
        } else {
          response = await Dio()
              .post(request.url(), options: options, data: request.params);
        }
      } else if (request.httpMethod() == HttpMethod.DELETE) {
        response = await Dio()
            .delete(request.url(), options: options, data: request.params);
      }
      // ignore: deprecated_member_use
    } on DioError catch (e) {
      response = e.response;
    }

    return await buildRes(response, request);
  }
}
